sap.ui.define([
    "sap/m/bbf41/Module/controller/BaseController",
    "sap/ui/model/json/JSONModel"
], function (BaseController, JSONModel) {
    "use strict";
    var oView;
    return BaseController.extend("sap.m.bbf41.Module.controller.RTB2", {
        onInit: function () {
            this.loadFoundryDataModel();
            var me = this;
            oView = me.getView();
            var oIconTabBar = oView.byId('IconTabBar');
            oIconTabBar.attachSelect(function () {
                me.handleRefresh();
            });
        },
        handlePressOpenMenu: function (oEvent) {
            var oButton = oEvent.getSource();
            // create menu only once
            if (!this._menu) {
                this._menu = sap.ui.xmlfragment(
                    "sap.m.bbf41.Module.fragment.Foundry",
                    this
                );
                this.getView().addDependent(this._menu);
            }
            var eDock = sap.ui.core.Popup.Dock;
            this._menu.open(this._bKeyboard, oButton, eDock.BeginTop, eDock.BeginBottom, oButton);
        },
        handleRefresh: function () {
            this.loadFoundryDataModel();
        },
        loadFoundryDataModel: function () {
            var me = this,
                oModel = new JSONModel(),
                oView = this.getView(),
                oCastingB38ATable = oView.byId('CastingB38ATable'),
                oCastingB38BTable = oView.byId('CastingB38BTable'),
                oCastingB48ATable = oView.byId('CastingB48ATable'),
                oCastingB48BTable = oView.byId('CastingB48BTable'),
                oCastingTotalTable = oView.byId('CastingTotalTable'),
                oMessageStrip = oView.byId('messageStrip');
            oCastingB38ATable.setBusy(true);
            oCastingB38BTable.setBusy(true);
            oCastingB48ATable.setBusy(true);
            oCastingB48BTable.setBusy(true);
            oCastingTotalTable.setBusy(true);
            oMessageStrip.setBusy(true);
            setTimeout(function () {
                jQuery.ajax({
                    url: '/NEP/ALS/api/rtb2?time='+Date.now(),
                    dataType: "json",
                    success: function (resp) {
                        var oData = me.buildTableData(resp);
                        oModel.setData(oData);
                        oView.setModel(oModel);
                    }.bind(this),
                    error: function () {
                        jQuery.sap.log.error("failed to load json");
                    },
                    complete: function () {
                        oCastingB38ATable.setBusy(false);
                        oCastingB38BTable.setBusy(false);
                        oCastingB48ATable.setBusy(false);
                        oCastingB48BTable.setBusy(false);
                        oCastingTotalTable.setBusy(false);
                        oMessageStrip.setBusy(false);
                    }
                });
            }, 768);
            return oModel;
        },
        onNavButtonPress: function () {
            this.getRouter().navTo('welcome');
        },
        handleMenuItemPress: function (oEvent) {
            var routeName = oEvent.getSource().data('area');
            this.getRouter().navTo(routeName);
        },
        buildTableData: function (resp) {
            var data = {
                "B38ACollection": [
                    {
                        "Type": "Target",
                        "Today": 0,
                        "CurrentWeek": 0
                    },
                    {
                        "Type": "Current",
                        "Today": 0,
                        "CurrentWeek": 0
                    },
                    {
                        "Type": "Forecast",
                        "Today": 0,
                        "CurrentWeek": 0
                    },
                    {
                        "Type": "Planned",
                        "Today": 0,
                        "CurrentWeek": 0
                    },
                    {
                        "Type": "Deviation",
                        "Today": 0,
                        "CurrentWeek": 0
                    }
                ],
                "B38BCollection": [
                    {
                        "Type": "Target",
                        "Today": 0,
                        "CurrentWeek": 0
                    },
                    {
                        "Type": "Current",
                        "Today": 0,
                        "CurrentWeek": 0
                    },
                    {
                        "Type": "Forecast",
                        "Today": 0,
                        "CurrentWeek": 0
                    },
                    {
                        "Type": "Planned",
                        "Today": 0,
                        "CurrentWeek": 0
                    },
                    {
                        "Type": "Deviation",
                        "Today": 0,
                        "CurrentWeek": 0
                    }
                ],
                "B48ACollection": [
                    {
                        "Type": "Target",
                        "Today": 0,
                        "CurrentWeek": 0
                    },
                    {
                        "Type": "Current",
                        "Today": 0,
                        "CurrentWeek": 0
                    },
                    {
                        "Type": "Forecast",
                        "Today": 0,
                        "CurrentWeek": 0
                    },
                    {
                        "Type": "Planned",
                        "Today": 0,
                        "CurrentWeek": 0
                    },
                    {
                        "Type": "Deviation",
                        "Today": 0,
                        "CurrentWeek": 0
                    }
                ],
                "B48BCollection": [
                    {
                        "Type": "Target",
                        "Today": 0,
                        "CurrentWeek": 0
                    },
                    {
                        "Type": "Current",
                        "Today": 0,
                        "CurrentWeek": 0
                    },
                    {
                        "Type": "Forecast",
                        "Today": 0,
                        "CurrentWeek": 0
                    },
                    {
                        "Type": "Planned",
                        "Today": 0,
                        "CurrentWeek": 0
                    },
                    {
                        "Type": "Deviation",
                        "Today": 0,
                        "CurrentWeek": 0
                    }
                ],
                "TotalCollection": [
                    {
                        "Type": "Target",
                        "TotalToday": 0,
                        "TotalWeek": 0
                    },
                    {
                        "Type": "Current",
                        "TotalToday": 0,
                        "TotalWeek": 0
                    },
                    {
                        "Type": "Forecast",
                        "TotalToday": 0,
                        "TotalWeek": 0
                    },
                    {
                        "Type": "Planned",
                        "TotalToday": 0,
                        "TotalWeek": 0
                    },
                    {
                        "Type": "Deviation",
                        "TotalToday": 0,
                        "TotalWeek": 0
                    }
                ],
                "LineRate": "0"
            };
            var po,
                dayTotal = 0;

            if (resp && resp['rtb2_data']) {
                $.each(resp['rtb2_data'], function (i, o) {
                    var cKey = i + 'Collection',
                        totalPo = data['TotalCollection'];
                    po = data[cKey];
                    dayTotal = (dayTotal || 0) + parseInt(o[1]['today']);
                    $.each(o, function (ii, oo) {
                        po[ii]['Today'] = oo['today'];
                        po[ii]['CurrentWeek'] = oo['current_week'];
                        totalPo[ii]['TotalToday'] += parseInt(oo['today']);
                        totalPo[ii]['TotalWeek'] += parseInt(oo['current_week']);
                    });
                });

                this.calcLineRate(data, dayTotal);
            }
            return data;
        },
        calcLineRate: function (data, dayTotal) {
            var date = new Date(),
                y = date.getFullYear(),
                m = date.getMonth() + 1,
                d = date.getDate(),
                paddingNum = function (n) {
                    if (n < 10) {
                        n = '0' + n;
                    }
                    return n;
                };
            var ds = y + '/' + paddingNum(m) + '/' + paddingNum(d) + ' 06:00:00',
                ts = (new Date(ds)).getTime() / 1000,
                nts = parseInt((new Date()).getTime() / 1000),
                nh = parseInt((nts - ts) / 360) / 10,
                rate = nh != 0 ? parseInt(dayTotal * 100 / nh) / 100 : 0;
            data['LineRate'] = rate + ' U/H';
        }
    });

});
